package controller.admin;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.GeneralUtil;

import model.dao.JPAHiberDAOFactory;
import model.dao.entity.BrandDAO;
import model.entity.Brand;

import com.google.gson.Gson;

/**
 * Servlet implementation class BrandContr
 */
public class BrandContr extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private BrandDAO brandDAO;

	public BrandContr() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		brandDAO = (BrandDAO) JPAHiberDAOFactory.getInstance().getBrandDAO();
		List<Brand> brList = brandDAO.selectAll();

		Gson gson = new Gson();
		String objectToTransfer = gson.toJson(brList);

		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.print(objectToTransfer);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String commnad = request.getParameter("command");
		brandDAO = (BrandDAO) JPAHiberDAOFactory.getInstance().getBrandDAO();

		if (commnad != null) {
			// Get json string from request
			String jsonObj = GeneralUtil.getJsonStringSimp(request);

			// Chuyen du lieu sang POJO
			Gson gson = new Gson();
			Brand thisBrand = gson.fromJson(jsonObj, Brand.class);


			if (commnad.equals("create")) {
				brandDAO.persist(thisBrand);

				response.setContentType("application/json");
				PrintWriter out = response.getWriter();
				out.print(gson.toJson(thisBrand));

			} else if (commnad.equals("delete")) {
				brandDAO.deleteByID(thisBrand.getId());
				
			} else if (commnad.equals("update")) {
				Brand dbBrand = brandDAO.findReference(thisBrand.getId());
				brandDAO.refresh(dbBrand);
				dbBrand.setInfo(thisBrand.getInfo());
				dbBrand.setName(thisBrand.getName());

				brandDAO.persist(dbBrand);
			}
		} 
	}

}
